package com.pirestupppai.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.pirestupppai.R;
import com.pirestupppai.base.BaseActivity;
import com.pirestupppai.bean.LoginUser;
import com.pirestupppai.bean.TupaiUser;
import com.pirestupppai.common.Constant;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.utils.OauthUtil;
import com.pirestupppai.utils.Utils;
import com.pirestupppai.utils.WeakReferenceHandler;
import com.pirestupppai.widgets.dialog.ProgressingDialog;

import java.util.HashMap;

import butterknife.BindView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * 登录页
 *
 * @author: xiaoluo
 * @date: 2017-03-01 17:28
 */
public class LoginActivity extends BaseActivity{

    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.input_phone_tv)
    TextView inputPhoneTv;
    @BindView(R.id.input_passwd_et)
    EditText passwdEt;
    @BindView(R.id.forget_passwd_btn)
    ImageView forgetIv;
    @BindView(R.id.login_btn)
    Button loginBtn;
    @BindView(R.id.weibo_login)
    ImageView weiboBtn;
    @BindView(R.id.qq_login)
    ImageView qqBtn;
    @BindView(R.id.weixin_login)
    ImageView weixinBtn;

    private static final int OAUTH_ERROR = 500;
    private static final int OAUTH_CANCEL = 600;
    private static final int OAUTH_SUCCESS = 700;

    private WeakReferenceHandler mHandler = new WeakReferenceHandler(this);
    private Platform mPlatform;
    private ProgressingDialog mDialog;
    private String mPhoneNum = "";

    @Override
    protected Context getActivityContext() {
        return this;
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initViews() {
        mPhoneNum = getIntent().getStringExtra(Constant.IntentKey.PHONE);
        inputPhoneTv.setText(mPhoneNum);
        mDialog = new ProgressingDialog(mContext);
    }

    @Override
    protected void initListeners() {
        loginBtn.setOnClickListener(this);
        forgetIv.setOnClickListener(this);
        backBtn.setOnClickListener(this);
        forgetIv.setOnClickListener(this);
        qqBtn.setOnClickListener(this);
        weiboBtn.setOnClickListener(this);
        weixinBtn.setOnClickListener(this);
    }

    @Override
    protected void initLogic() {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_btn:
                loginBtn.setClickable(false);
                phoneLogin();
                break;
            case R.id.back_btn:
                finish();
                break;
            case R.id.forget_passwd_btn:
                Intent intent = new Intent(mContext, ResetPasswdActivity.class);
                intent.putExtra(Constant.IntentKey.PHONE, mPhoneNum);
                startActivity(intent);
                break;
            case R.id.qq_login:
                oauthLogin(OauthUtil.PLATFORM_QQ);
                break;
            case R.id.weibo_login:
                oauthLogin(OauthUtil.PLATFORM_WEIBO);
                break;
            case R.id.weixin_login:
                oauthLogin(OauthUtil.PLATFORM_WECHAT);
                break;
        }
    }


    @Override
    public boolean handleMessage(Message msg) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        switch (msg.what) {
            case OAUTH_ERROR:
                Utils.showToast("授权出错");
                break;
            case OAUTH_CANCEL:
                Utils.showToast("取消");
                break;
            case OAUTH_SUCCESS:
                OauthUtil.oauthLogin(mContext, mPlatform, (String) msg.obj);
                break;
        }
        return super.handleMessage(msg);
    }

    /**
     * 手机号登录
     */
    private void phoneLogin() {
        if (validate()) {
            NetworkRequest.getInstance().phoneLogin(mPhoneNum, passwdEt.getText().toString().trim(),
                    new TupaiSubscriber<TupaiUser>(mContext) {
                        @Override
                        protected void requestSuccess(TupaiUser loginUser) {
                            loginBtn.setClickable(true);
                            LoginUser.getInstance().initFromResponse(loginUser);
                            Intent intent = new Intent(mContext, MainActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }

                        @Override
                        protected void requestError(String error) {
                            loginBtn.setClickable(true);
                        }
                    });
        }
    }

    private boolean validate() {
        if (TextUtils.isEmpty(passwdEt.getText().toString().trim())) {
            Utils.showToast("请填写登录密码");
            passwdEt.requestFocus();
            loginBtn.setClickable(true);
            return false;
        }

        if (passwdEt.length() < 6 || passwdEt.length() > 16) {
            Utils.showToast("密码6-16位字符");
            loginBtn.setClickable(true);
            return false;
        }
        return true;
    }


    /**
     * 第三方授权登录
     */
    private void oauthLogin(final String name) {
        mDialog.show();
        Platform platform = null;
        switch (name) {
            case OauthUtil.PLATFORM_QQ:
                platform = ShareSDK.getPlatform(QQ.NAME);
                break;
            case OauthUtil.PLATFORM_WEIBO:
                platform = ShareSDK.getPlatform(SinaWeibo.NAME);
                break;
            case OauthUtil.PLATFORM_WECHAT:
                platform = ShareSDK.getPlatform(Wechat.NAME);
                break;
        }
        platform.SSOSetting(false); //设置false表示使用SSO授权方式,优先调用客户端
        //authorize与showUser单独调用一个即可
        platform.authorize(); //单独授权,OnComplete返回的hashmap是空的
//        platform.showUser(null);//授权并获取用户信息
        if (platform.isAuthValid()) {
            platform.removeAccount(true);
        }

        final Message message = Message.obtain();
        message.obj = name;
        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                mPlatform = platform;
                message.what = OAUTH_SUCCESS;
                mHandler.sendMessage(message);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                message.what = OAUTH_ERROR;
                mHandler.sendMessage(message);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                message.what = OAUTH_CANCEL;
                mHandler.sendMessage(message);
            }
        });
    }
}
